// this is a program that tests device characterization
// it reads in the test file provided by the user and makes requests to the host name thats defined in the command line parameter
// by sending the pragma headers, it extracts the value from the session variables

import java.io.*;
import java.util.*;
import java.net.*;

public class sbscript
{
    public static void main(String [] args) throws IOException
    {
        URL urlAkamai;
        String deviceFileName;
        BufferedReader br, br2;
        StringBuffer sb;
        String s, s2, s3;
        StringTokenizer st, st2; 
        String useragent, permission;
        String headerName, headerValue;
        HttpURLConnection conn;

        // init variables
        s = "";
        s2 = "";
        s3 = "";
        useragent = "";
        permission = "";
        headerValue = "";
        headerName = "";
        
        // verify the correct command line requests
        if (args.length != 2)
        {
            System.out.println("Usage: java sbscript <url> <devicefile>");
            System.exit(-1);

        } // end if

        // set up the initial variables from the args
        urlAkamai = new URL(args[0]);
        deviceFileName = args[1];
  
        // open the connection to the test file
        br = new BufferedReader(new FileReader(deviceFileName));
                    
        // read line by line from the test script
        while ( (s = br.readLine()) != null )
        {
            // parse out the line using | as the token
            st = new StringTokenizer(s, "|");
            
            // insert check to ensure that there are 2 tokens only
            if (st.countTokens() == 2)
            {
                useragent = st.nextToken();
                permission = st.nextToken();
               
                // remove any leading or trailing spaces and clean up input
                useragent = useragent.trim();
                permission = permission.trim();
                
                // set up the parameters to make a "curl" request
                // sending only the pragma and custom user-agent headers
                // open connection to the url
                conn = (HttpURLConnection) urlAkamai.openConnection();
                conn.setRequestMethod("GET");
                conn.addRequestProperty("Pragma", "akamai-x-get-extracted-values, akamai-x-get-cache-key");
                conn.setRequestProperty("User-Agent", useragent);

                // some problem happened
                if (conn.getResponseCode() != 200)
                {
                    throw new RuntimeException("Error code : " + conn.getResponseCode());
                
                } // end if

                br2 = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                sb = new StringBuffer();
                
                // this is the loop that receives the response from the edge
                while ((s2 = br2.readLine()) != null)
                {
                    sb.append(s2);

                } // end while

//                System.out.println("User-agent: " + useragent);
                
                // loop through all the response headers
                for (int i = 1;; i++)
                {
                   headerName = conn.getHeaderFieldKey(i);
                   headerValue = conn.getHeaderField(i);
                
                    // there's nothing here and the loop is over
                    if (headerName == null && headerValue == null)
                    {
                        break;
                    } // end if
                                       
                    // need to extract the SB_PERMISSION header 
                    if (headerName.equals("X-Akamai-Session-Info"))
                    {
                        if ( (headerValue.contains("SB_PERMISSION"))  )
                        {                           
                            // split the string
                            st2 = new StringTokenizer(headerValue, ";=");

                            // consume 4 tokens
                            if (st2.countTokens() == 4)
                            {
                                s3 = st2.nextToken();
                                s3 = st2.nextToken();
                                s3 = st2.nextToken();
                                s3 = st2.nextToken();

                            } // end if
                            
                            // s3 now contains the value in the header. it will be some form of allow or deny
                            if (s3.contains(permission))
                            {
                                System.out.println(useragent + " = pass");
                            }
                            else
                            {
                                System.out.println(useragent + " = FAILED");
                            }
                                                                           
                        } // end if

                    } // end if
                    
                  
                } // end for   
                System.out.println("----------");

                conn.disconnect();

            } // end if

        } // end while    

        // clean up everything
        br.close();

    } // end main

} // end class